var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const { User, Role } = require('../model/model');

// JWT密钥
const JWT_SECRET = 'rbac-system-secret-key';

// 验证Token中间件
const authMiddleware = (req, res, next) => {
  const token = req.header('x-auth-token');
  
  if (!token) {
    return res.status(401).json({ success: false, message: '无访问权限，请先登录' });
  }
  
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    req.user = decoded.user;
    next();
  } catch (err) {
    res.status(401).json({ success: false, message: '无效的Token' });
  }
};

// 权限检查中间件
const checkPermission = (permission) => {
  return (req, res, next) => {
    if (req.user.role === '老板' || req.user.permissions?.includes('all') || req.user.permissions?.includes(permission)) {
      next();
    } else {
      res.status(403).json({ success: false, message: '权限不足' });
    }
  };
};

// 检查是否为老板的中间件
const checkOwnerPermission = (req, res, next) => {
  if (req.user.role === '老板') {
    next();
  } else {
    res.status(403).json({ success: false, message: '只有老板可以执行此操作' });
  }
};

// 检查是否为老板或管理员的中间件
const checkManagerPermission = (req, res, next) => {
  if (req.user.role === '老板' || req.user.role === '管理员') {
    next();
  } else {
    res.status(403).json({ success: false, message: '权限不足' });
  }
};

// 请假申请模型（这里使用简单的内存存储，实际项目中应该使用数据库）
let leaveRequests = [];
let requestIdCounter = 1;

// 获取请假申请列表
router.get('/', authMiddleware, checkManagerPermission, async function(req, res) {
  try {
    // 格式化请假申请数据，添加员工姓名
    const formattedRequests = await Promise.all(leaveRequests.map(async (request) => {
      try {
        const user = await User.findById(request.employeeId);
        return {
          ...request,
          employeeName: user ? user.username : '未知员工'
        };
      } catch (error) {
        return {
          ...request,
          employeeName: '未知员工'
        };
      }
    }));
    
    res.json({
      success: true,
      data: formattedRequests
    });
  } catch (error) {
    console.error('获取请假申请列表失败:', error);
    res.status(500).json({ success: false, message: '获取请假申请列表失败', error: error.message });
  }
});

// 创建请假申请
router.post('/', authMiddleware, checkManagerPermission, async function(req, res) {
  try {
    const { employeeId, type, startDate, endDate, reason, category, restDate } = req.body;
    
    // 验证必填字段
    if (!employeeId || !reason) {
      return res.status(400).json({ success: false, message: '员工ID和原因为必填项' });
    }
    
    // 验证员工是否存在
    const employee = await User.findById(employeeId);
    if (!employee) {
      return res.status(400).json({ success: false, message: '员工不存在' });
    }
    
    // 创建请假申请
    const newRequest = {
      id: `LR${String(requestIdCounter++).padStart(3, '0')}`,
      employeeId: employeeId,
      type: type || 'other',
      startDate: startDate || restDate,
      endDate: endDate || restDate,
      reason: reason,
      category: category || 'leave',
      status: 'pending',
      createTime: new Date(),
      createBy: req.user.id || req.user.username
    };
    
    leaveRequests.push(newRequest);
    
    res.status(201).json({
      success: true,
      message: '请假申请创建成功',
      data: {
        ...newRequest,
        employeeName: employee.username
      }
    });
  } catch (error) {
    console.error('创建请假申请失败:', error);
    res.status(500).json({ success: false, message: '创建请假申请失败', error: error.message });
  }
});

// 审批请假申请
router.put('/:id/approve', authMiddleware, checkOwnerPermission, async function(req, res) {
  try {
    const { id } = req.params;
    
    // 查找请假申请
    const requestIndex = leaveRequests.findIndex(req => req.id === id);
    if (requestIndex === -1) {
      return res.status(404).json({ success: false, message: '请假申请不存在' });
    }
    
    // 更新状态为已批准
    leaveRequests[requestIndex].status = 'approved';
    leaveRequests[requestIndex].approveTime = new Date();
    leaveRequests[requestIndex].approveBy = req.user.id || req.user.username;
    
    res.json({
      success: true,
      message: '请假申请已批准',
      data: leaveRequests[requestIndex]
    });
  } catch (error) {
    console.error('审批请假申请失败:', error);
    res.status(500).json({ success: false, message: '审批请假申请失败', error: error.message });
  }
});

// 拒绝请假申请
router.put('/:id/reject', authMiddleware, checkOwnerPermission, async function(req, res) {
  try {
    const { id } = req.params;
    const { rejectReason } = req.body;
    
    // 查找请假申请
    const requestIndex = leaveRequests.findIndex(req => req.id === id);
    if (requestIndex === -1) {
      return res.status(404).json({ success: false, message: '请假申请不存在' });
    }
    
    // 更新状态为已拒绝
    leaveRequests[requestIndex].status = 'rejected';
    leaveRequests[requestIndex].rejectTime = new Date();
    leaveRequests[requestIndex].rejectBy = req.user.id || req.user.username;
    leaveRequests[requestIndex].rejectReason = rejectReason || '未提供拒绝原因';
    
    res.json({
      success: true,
      message: '请假申请已拒绝',
      data: leaveRequests[requestIndex]
    });
  } catch (error) {
    console.error('拒绝请假申请失败:', error);
    res.status(500).json({ success: false, message: '拒绝请假申请失败', error: error.message });
  }
});

// 获取请假申请统计
router.get('/stats', authMiddleware, checkManagerPermission, async function(req, res) {
  try {
    const total = leaveRequests.length;
    const pending = leaveRequests.filter(req => req.status === 'pending').length;
    const approved = leaveRequests.filter(req => req.status === 'approved').length;
    const rejected = leaveRequests.filter(req => req.status === 'rejected').length;
    
    res.json({
      success: true,
      data: {
        total,
        pending,
        approved,
        rejected
      }
    });
  } catch (error) {
    console.error('获取请假申请统计失败:', error);
    res.status(500).json({ success: false, message: '获取请假申请统计失败', error: error.message });
  }
});

module.exports = router; 